from django.shortcuts import render

from django.http import HttpResponse
from django.views.generic import View

from JetBrainsLicenseServer.libraries import LicenseSigner


def error404(request):
    return HttpResponse('404 - Not Found', content_type='text/plain', status=404)


def error500(request):
    return HttpResponse('500 - Internal Server Error', content_type='text/plain', status=500)


class ObtainTicket(View):
    @staticmethod
    def get(request, *args, **kwargs):
        get_data = {
            'build_date': request.GET.get('buildDate', ''),
            'client_version': request.GET.get('clientVersion', ''),
            'host_name': request.GET.get('hostName', ''),
            'machine_id': request.GET.get('machineId', ''),
            'product_code': request.GET.get('productCode', ''),
            'product_family_id': request.GET.get('productFamilyId', ''),
            'salt': request.GET.get('salt', ''),
            'secure': request.GET.get('secure', ''),
            'username': request.GET.get('userName', ''),
            'version': request.GET.get('version', ''),
            'version_number': request.GET.get('versionNumber', '')
        }

        prolongation_period = 607875500

        xml_response = [
            '<ObtainTicketResponse><message></message><prolongationPeriod>',
            str(prolongation_period),
            '</prolongationPeriod><responseCode>OK</responseCode><salt>',
            str(get_data['salt']),
            '</salt><ticketId>1</ticketId><ticketProperties>licensee=',
            get_data['username'].encode('UTF-8'),
            '\tlicenseType=0\t',
            '</ticketProperties></ObtainTicketResponse>'
        ]

        xml_response = ''.join(xml_response)

        license_signer = LicenseSigner()
        xml_signature = license_signer.generate_signature(xml_response)

        return HttpResponse('%s%s' % (xml_signature, xml_response), content_type='text/xml', status=200)

    @staticmethod
    def post(request, *args, **kwargs):
        return HttpResponse('401 - Forbidden', content_type='text/plain', status=401)


class Ping(View):
    @staticmethod
    def get(request, *args, **kwargs):
        xml_response = [
            '<PingResponse><message></message><responseCode>OK</responseCode><salt>',
            str(request.GET.get('salt', '')),
            '</salt></PingResponse>'
        ]

        xml_response = ''.join(xml_response)

        license_signer = LicenseSigner()
        xml_signature = license_signer.generate_signature(xml_response)

        return HttpResponse('%s%s' % (xml_signature, xml_response), content_type='text/xml', status=200)

    @staticmethod
    def post(request, *args, **kwargs):
        return HttpResponse('401 - Forbidden', content_type='text/plain', status=401)
